/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.persistence.c14n;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Tacoma Four
 */
final class DateArrayC14NHandler extends AbstractC14NHandler
{
    @Override
    public Object fromC14N(byte[] bytes)
    {
        List<Date> dateList = new ArrayList<Date>();
        DataInputStream dateDis = new DataInputStream(new ByteArrayInputStream(bytes));

        try
        {
            while (true)
            {
                dateList.add(new Date(dateDis.readLong()));
            }
        } catch (EOFException ignore)
        {

        } catch (IOException e)
        {
            e.printStackTrace();
        }

        Date[] dateValues = new Date[dateList.size()];
        return dateList.toArray(dateValues);

    }

    @Override
    public byte[] toC14N(Object object)
    {
        byte[] dateBytes = new byte[0];

        Date[] dateValues = (Date[]) object;
        ByteArrayOutputStream dateBaos = new ByteArrayOutputStream();
        DataOutputStream dateDos = new DataOutputStream(dateBaos);

        String dateHeader = PACKED_BLOB_PREFIX + transposeClassName(Date[].class.getName()) + PACKED_BLOB_SUFFIX;
        byte[] dateHeaderBytes = dateHeader.getBytes();
        try
        {
            dateDos.write(dateHeaderBytes, 0, dateHeaderBytes.length);

            for (Date curValue : dateValues)
            {
                dateDos.writeLong(curValue.getTime());
            }

            dateDos.flush();
            dateDos.close();
            dateBytes = dateBaos.toByteArray();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return dateBytes;
    }
}
